package com.microservice.order.service;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.microservice.common.R;
import com.microservice.common.ServiceException;
import com.microservice.order.dto.OrderDTO;
import com.microservice.order.entity.OrderEntity;
import com.microservice.order.mapper.OrderMapper;
import com.microservice.order.param.OrderParam;
import com.microservice.product.dto.ProductInfoDTO;
import com.microservice.product.feign.ProductClient;
import com.microservice.product.param.ProductReduceParam;
import io.seata.spring.annotation.GlobalTransactional;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.modelmapper.ModelMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.UUID;

/**
 * write something please~
 *
 * @author huangrz
 * @since 2021/9/14
 **/
@Service
@Slf4j
public class OrderService extends ServiceImpl<OrderMapper, OrderEntity> {

    @Autowired
    private ProductClient productClient;
    @Autowired
    private ModelMapper modelMapper;

    @GlobalTransactional
    public R<OrderDTO> order(OrderParam param) {
        // 查询产品是否存在
        R<ProductInfoDTO> r = productClient.getById(param.getPid());
        if (!r.isOk()) {
            throw new ServiceException("您要购买的产品已下架，请重新选择其他产品。");
        }
        ProductInfoDTO productInfoDTO = r.getData();

        if (productInfoDTO.getCount() < param.getQuantity()) {
            throw new ServiceException("您要购买的产品库存不足。");
        }

        // 下单
        OrderEntity orderEntity = new OrderEntity();
        orderEntity.setName(productInfoDTO.getName());
        orderEntity.setQuantity(param.getQuantity());
        orderEntity.setPrice(productInfoDTO.getUnitPrice().multiply(BigDecimal.valueOf(param.getQuantity())));
        boolean bsave = saveOrder(orderEntity);
        if (!bsave) {
            throw  new ServiceException("订单保存失败！");
        }
        // 扣减库存
        ProductReduceParam productReduceParam = ProductReduceParam.builder()
                .count(param.getQuantity())
                .id(productInfoDTO.getId())
                .build();
        R<Boolean> r3 = productClient.reduce(productReduceParam);
        if (!r3.isOk()) {
            throw new ServiceException("下单失败，请稍后再试！");
        }
        if (!r3.getData()) {
            log.error("产品扣减库存失败：{}", JSONObject.toJSONString(param));
            throw new ServiceException("下单失败，请稍后再试！");
        }

        return R.ok(modelMapper.map(orderEntity,OrderDTO.class));
    }

    public boolean saveOrder(OrderEntity orderEntity) {
        if (StringUtils.isEmpty(orderEntity.getOrderNo())) {
            orderEntity.setOrderNo(UUID.randomUUID().toString().replaceAll("-", ""));
        }
        return this.save(orderEntity);
    }
}
